#include "mainwindow.h"
#include "ui_mainwindow.h"

MainWindow::MainWindow(QWidget *parent) :
    QMainWindow(parent),
    ui(new Ui::MainWindow)
{
    ui->setupUi(this);
    arduinoConnection = new QTcpSocket(this);
    connect(arduinoConnection, SIGNAL(connected()), this, SLOT(socketConnected()));
    connect(arduinoConnection, SIGNAL(readyRead()), this, SLOT(newData()));
}

MainWindow::~MainWindow()
{
    delete ui;
}

void MainWindow::on_pbConnect_clicked()
{
    arduinoConnection->connectToHost("10.1.1.10", 2000);
}

void MainWindow::socketConnected()
{
    ui->listWidget->addItem("Connected");
}

void MainWindow::newData()
{
    ui->listWidget->addItem((QString)arduinoConnection->readAll());
}

void MainWindow::on_pushButton_clicked()
{
    if(arduinoConnection->isWritable()){
        char array[255];
        strcpy(array, ui->lineEdit->text().toAscii().constData());
        arduinoConnection->write(array);
        arduinoConnection->write("\r");

        ui->lineEdit->text() = "";
    }
}

void MainWindow::closeEvent(QCloseEvent *){
    if(arduinoConnection->isOpen()){
        arduinoConnection->write("close\r");
        arduinoConnection->disconnectFromHost();
    }
    delete arduinoConnection;
}
